<?php
class TimedsController extends AppController {

	var $name = 'Timeds';

	function isAuthorized(){
		if($this->Auth->user('group_id') == $this->Session->read('Settings.adminPermission')){		//admin jogosultságú júzerek
			return true;
		}
		//free user / premium user / business user
		if(in_array($this->action, array(
													'send', 'delete'
													))){
			return true;
		}
		return false;		//minden más tiltva
	}

	function index(){
		$this->Timed->recursive = 0;
		$messages = $this->Timed->find('all',
										array(
											'conditions' => array('Timed.user_id' => $this->Auth->user('id')),
											'order' => 'time DESC',
											'recursive' => -1));

		$accounts = $this->Timed->User->Account->find('all', array('conditions' => array('Account.user_id' => $this->Auth->user('id'))));
		foreach($accounts as $i => $a){
			$accs[$a['Account']['id']] = $a;
		}
		$accounts = $accs;
		
		foreach($messages as $i => $m){
			$messages[$i]['Message'] = $messages[$i]['Timed'];
			$messages[$i]['Message']['created'] = $messages[$i]['Message']['time'];
			unset($messages[$i]['Timed'], $messages[$i]['Message']['time']);
			
			if($m['Timed']['account_ids']){
				$accIds = unserialize($m['Timed']['account_ids']);
				foreach($accIds as $aId){
					//Community.name, username, avatar
					$messages[$i]['Account'][] = array(
															'id' => $aId,
															'username' => $accounts[$aId]['Account']['username'],
															'Community' => array('name' => $accounts[$aId]['Community']['name'])
															);
				}
			}
			else
				unset($messages[$i]);
		}
		$this->set('messages', $messages);
	}

/*
 * Sends messages to the timed queue
*/
	function add(){
		$errorz = null;
		if($this->data){
			/*
			Array(
				[Message] => Array(
	            [message] => Sociall időzített küldés teszt
	            [date] => 2009-11-08
	            [time] => 14:10)
			   [Account] => Array(
	            [Account_0] => 0
	            [Account_1] => 0
	            [Account_2] => 2)
				)
			*/
			$isAjax = $this->RequestHandler->isAjax();
			
			App::import('Sanitize');

			$this->data['Message']['message'] = Sanitize::html($this->data['Message']['message']);

			//is there message?
			if(!$this->data['Message']['message']){
				$this->_sendError(__('There is no message. How could I send it, baby?', true), $isAjax);
			}

			//at least 1 account supposed to be checked
			$c = 0;
			foreach($this->data['Account'] as $key => $value){
				if($value){
					$c += $value;
					$accounts[] = intval($value);
					$acc = $this->Timed->User->Account->find('first',
																 array(
																	'conditions' => array(
																							'Account.id' => $value,
																							'Account.user_id' => $this->Auth->user('id'))
																	));
					if(isset($acc['Account'])){
						$details[] = array(
										'community' => $acc['Community']['name'],	//community.name
										'extra' => 'timed',
										'targetuser' => $acc['Account']['username'],
										'username' => $acc['Account']['username']);	//kinek a nevében van elküldve account.user.name
					}
					else
						$this->log(__($this->Auth->user('id') . ' tried to send a timed message to account id ' . $value . ' but it belongs to someone else', LOG_DEBUG));
				}
				unset($this->data['Account']);
			}
			
			if(!$c){
				$this->_sendError(__('You should check at least one account to send the message.', true), $isAjax);
			}
			else
				$this->data['Message']['account_ids'] = serialize($accounts);
			
			//is there date & time and valid and not in the past?
			if($this->data['Message']['date'] && $this->data['Message']['time']){
				App::import('Helper', 'EasyDate');
		      $easyDate = new easyDateHelper();
				$date = $easyDate->change($this->data['Message']['date']);
				//$this->data['Message']['time'] = $easyTime->change($this->data['Message']['time']);
				$this->data['Message']['time'] = $date . ' ' . Sanitize::clean($this->data['Message']['time']);
				if($this->data['Message']['time'] < date('Y-m-d H:i'))
					$this->_sendError(__('The given time is in the past. Could not send the message', true), $isAjax);
			}
			else
				$this->_sendError(__('There is no date or time', true), $isAjax);
			
			//it looks ok let's save & send the messages
			//save the messages to the database
			$this->data['Message']['user_id'] = $this->Auth->user('id');
			$this->data['Timed'] = $this->data['Message'];
			unset($this->data['Message']);
			if(!$this->Timed->save($this->data)){
				$this->_sendError(__('Timed message can not saved', true), $isAjax);
			}
			else
				$this->set('timed', array(
												'timed' => $this->data['Timed']['time'],
												'details' => $details,
												'created' => date('Y-m-d H:i:s')));

			if($errorz)
				$this->log('send messages: ' . $errorz, LOG_DEBUG);
			
			if(!$isAjax)
				$this->redirect('/');
		}
		else{
			$this->_sendError(__('No data to send to queue', true), $isAjax);
		}
		
	}
	
	function _sendError($errorz, $isAjax = true){
		$this->set('errorz', $errorz);
		if($isAjax){
			$this->render();
		}
		else{
			$this->redirect('/');
		}
	}

/*	function edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid Timed', true));
			$this->redirect(array('action'=>'index'));
		}
		if (!empty($this->data)) {
			if ($this->Timed->save($this->data)) {
				$this->Session->setFlash(__('The Timed has been saved', true));
				$this->redirect(array('action'=>'index'));
			} else {
				$this->Session->setFlash(__('The Timed could not be saved. Please, try again.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->Timed->read(null, $id);
		}
		$users = $this->Timed->User->find('list');
		$this->set(compact('users'));
	}*/

/*
 * Delete timed message
*/
	function delete($id = null){
		if(!$id)
			$deleted = array('error' => __('Nothing to delete', true));
		else{
			//check if the id belongs to the user
			$t = $this->Timed->find('first',
											array(
												'conditions' => array('id' => $id),
												'recursive' => -1));
			
			if($t['Timed']['user_id'] == $this->Auth->user('id')){
				if($this->Timed->del($id)){
					$deleted = array('deleted' => true);
				}
			}
			else
				$deleted = array('error' => __('You can not delete a message what is not yours', true));
		}
		$this->set('deleted', $deleted);
	}


	function admin_index() {
		$this->Timed->recursive = 0;
		$this->set('timeds', $this->paginate());
	}

/*	function admin_add() {
		if (!empty($this->data)) {
			$this->Timed->create();
			if ($this->Timed->save($this->data)) {
				$this->Session->setFlash(__('The Timed has been saved', true));
				$this->redirect(array('action'=>'index'));
			} else {
				$this->Session->setFlash(__('The Timed could not be saved. Please, try again.', true));
			}
		}
		$users = $this->Timed->User->find('list');
		$this->set(compact('users'));
	}

	function admin_edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid Timed', true));
			$this->redirect(array('action'=>'index'));
		}
		if (!empty($this->data)) {
			if ($this->Timed->save($this->data)) {
				$this->Session->setFlash(__('The Timed has been saved', true));
				$this->redirect(array('action'=>'index'));
			} else {
				$this->Session->setFlash(__('The Timed could not be saved. Please, try again.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->Timed->read(null, $id);
		}
		$users = $this->Timed->User->find('list');
		$this->set(compact('users'));
	}

	function admin_delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for Timed', true));
			$this->redirect(array('action'=>'index'));
		}
		if ($this->Timed->del($id)) {
			$this->Session->setFlash(__('Timed deleted', true));
			$this->redirect(array('action'=>'index'));
		}
	}*/
}
?>